Introduction to Aggregate Functions in MySQL
Course: MySQL Training
Topic: Introduction to Aggregate Functions
Course Link: MySQL Training Course
Demo Link: Register for a Course Demo
1. Introduction to Aggregate Functions
Aggregate functions are built-in MySQL functions that perform calculations on multiple rows or a collection of values and return a single result. They are widely used in database reporting, business analysis, financial calculations, sales summaries, employee statistics, inventory management, and data analytics.
For example, a company may store thousands of sales transactions in a database. Instead of retrieving every transaction and calculating the total manually, an aggregate function can calculate the total revenue directly from the table. Similarly, a school can calculate the average marks of students, an organization can count its employees, and a store can identify its highest and lowest product prices.
The most commonly used MySQL aggregate functions are:
COUNT() — counts rows or non-NULL values.
SUM() — calculates the total of numeric values.
AVG() — calculates the average of numeric values.
MIN() — returns the minimum value.
MAX() — returns the maximum value.
Aggregate functions are frequently combined with SQL clauses such as WHERE, GROUP BY, HAVING, and ORDER BY to create useful summaries and reports.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand the meaning and purpose of aggregate functions in MySQL.
- Identify the most frequently used aggregate functions.
- Use COUNT(), SUM(), AVG(), MIN(), and MAX() in SQL queries.
- Understand the difference between COUNT(*) and COUNT(column).
- Work with NULL values in aggregate calculations.
- Apply aggregate functions with WHERE and GROUP BY.
- Filter grouped results using HAVING.
- Sort aggregate results using ORDER BY.
- Use DISTINCT to calculate results based on unique values.
- Create practical reports using aggregate functions.
3. What Are Aggregate Functions?
3.1 Definition
An aggregate function processes multiple values and returns one summarized result. Depending on the query, that result may represent an entire table, a filtered set of rows, or each group created by GROUP BY.
For example, consider a table containing the following sales amounts:
| Sale ID |
Product |
Amount |
| 1 |
Laptop |
50000 |
| 2 |
Mouse |
1000 |
| 3 |
Keyboard |
2000 |
| 4 |
Monitor |
15000 |
The SUM() function can calculate the total sales amount of these four records, while COUNT() can count the records and AVG() can calculate their average amount.
SELECT
COUNT(*) AS total_sales,
SUM(amount) AS total_revenue,
AVG(amount) AS average_sale,
MIN(amount) AS smallest_sale,
MAX(amount) AS largest_sale
FROM sales;
This query returns one row containing five summarized values instead of returning all four individual sales records.
3.2 Why Are Aggregate Functions Important?
- Data summarization: Convert large datasets into meaningful totals and statistics.
- Business reporting: Calculate revenue, expenses, orders, and product performance.
- Decision-making: Identify the highest-selling products and average transaction values.
- Performance analysis: Compare departments, regions, categories, or time periods.
- Data validation: Count records and inspect missing values.
- Dashboard development: Prepare summarized data for charts, reports, and analytical dashboards.
4. Types of Aggregate Functions in MySQL
| Function |
Purpose |
Example |
| COUNT() |
Counts rows or non-NULL values. |
COUNT(*) |
| SUM() |
Adds numeric values. |
SUM(salary) |
| AVG() |
Calculates the average of numeric values. |
AVG(marks) |
| MIN() |
Returns the smallest value. |
MIN(price) |
| MAX() |
Returns the largest value. |
MAX(price) |
| COUNT(DISTINCT) |
Counts unique non-NULL values or combinations. |
COUNT(DISTINCT city) |
| GROUP_CONCAT() |
Combines non-NULL values into a string. |
GROUP_CONCAT(product_name) |
This topic focuses mainly on COUNT(), SUM(), AVG(), MIN(), and MAX(), which form the foundation of aggregate calculations in MySQL.
5. Understanding the Sample Database
To understand aggregate functions, create a sample employee table and insert some records. The same table will be used throughout these notes.
5.1 Create the Employees Table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10,2),
bonus DECIMAL(10,2),
city VARCHAR(50)
);
The table contains employee details, including department, salary, bonus, and city.
5.2 Insert Sample Records
INSERT INTO employees
(employee_id, employee_name, department, salary, bonus, city)
VALUES
(1, 'Aarav', 'IT', 50000, 5000, 'Mumbai'),
(2, 'Priya', 'HR', 40000, 3000, 'Pune'),
(3, 'Rohan', 'IT', 60000, NULL, 'Mumbai'),
(4, 'Neha', 'Finance', 55000, 4000, 'Delhi'),
(5, 'Kabir', 'HR', 35000, NULL, 'Pune'),
(6, 'Meera', 'Finance', 65000, 6000, 'Mumbai'),
(7, 'Ishaan', 'IT', 45000, 2000, 'Delhi'),
(8, 'Ananya', 'Sales', 48000, 3500, 'Pune');
5.3 View the Records
SELECT *
FROM employees;
The table now contains eight employee records. Some employees have NULL bonus values. These NULL values will help demonstrate how aggregate functions handle missing data.
6. COUNT() Function
6.1 What Is COUNT()?
The COUNT() function counts rows or values according to the expression supplied. It is commonly used to calculate the number of employees, customers, orders, products, or other records in a database.
6.2 Syntax of COUNT()
COUNT(*)
COUNT(expression)
COUNT(DISTINCT expression)
6.3 COUNT(*) — Count All Rows
COUNT(*) counts all rows included in the query result, regardless of whether individual columns contain NULL values.
SELECT COUNT(*) AS total_employees
FROM employees;
Expected result: 8
This query counts all eight employee records.
6.4 COUNT(column) — Count Non-NULL Values
COUNT(column) counts rows where the specified column is not NULL. Rows containing NULL in that column are excluded from the count.
SELECT COUNT(bonus) AS employees_with_bonus_value
FROM employees;
Expected result: 6
Only six employees have a non-NULL bonus value. An employee whose bonus is zero would still be counted because zero is not NULL.
6.5 COUNT(DISTINCT column)
COUNT(DISTINCT column) counts unique non-NULL values in a column. Duplicate values are counted only once.
SELECT COUNT(DISTINCT department) AS unique_departments
FROM employees;
Expected result: 4
The departments are IT, HR, Finance, and Sales. Each department is counted once, even when multiple employees belong to the same department.
6.6 Counting Records with Conditions
COUNT() can be combined with WHERE to count records matching a particular condition.
SELECT COUNT(*) AS it_employees
FROM employees
WHERE department = 'IT';
Expected result: 3
This query counts employees who belong to the IT department.
6.7 Counting Employees by City
SELECT
city,
COUNT(*) AS employee_count
FROM employees
GROUP BY city;
This query calculates the number of employees in each city. Mumbai, Pune, and Delhi appear as separate groups.
7. SUM() Function
7.1 What Is SUM()?
The SUM() function calculates the total of numeric values in a column or expression. It is commonly used for total salaries, sales revenue, expenses, quantities sold, bonuses, and order amounts.
7.2 Syntax of SUM()
SUM(expression)
SUM(DISTINCT expression)
7.3 Calculate Total Salary
SELECT SUM(salary) AS total_salary
FROM employees;
Expected result: 398000.00
The query adds the salaries of all eight employees.
7.4 Calculate Total Bonuses
SELECT SUM(bonus) AS total_bonus
FROM employees;
Expected result: 23500.00
SUM(bonus) ignores NULL bonus values and adds the available numeric values. If every bonus value were NULL, SUM(bonus) would return NULL.
7.5 Calculate Total Salary for a Department
SELECT SUM(salary) AS it_total_salary
FROM employees
WHERE department = 'IT';
Expected result: 155000.00
This query calculates the combined salaries of the three IT employees.
7.6 SUM() with GROUP BY
GROUP BY divides records into groups. SUM() then calculates a separate total for each group.
SELECT
department,
SUM(salary) AS department_salary
FROM employees
GROUP BY department;
This query returns one row per department with its total salary. It is useful for departmental budget reports and payroll analysis.
7.7 SUM(DISTINCT expression)
SUM(DISTINCT expression) adds only distinct numeric values. Duplicate values are included once rather than being added repeatedly.
SELECT SUM(DISTINCT salary) AS distinct_salary_total
FROM employees;
Use SUM(DISTINCT) only when removing duplicate numeric values is part of the intended calculation. It is not a general way to eliminate duplicate records from a report because different employees can legitimately have the same salary.
8. AVG() Function
8.1 What Is AVG()?
The AVG() function calculates the arithmetic mean of numeric values. It adds the non-NULL values and divides the total by the number of non-NULL values.
For example, if three students score 70, 80, and 90, their average score is:
(70 + 80 + 90) / 3 = 80
8.2 Syntax of AVG()
AVG(expression)
AVG(DISTINCT expression)
8.3 Calculate Average Salary
SELECT AVG(salary) AS average_salary
FROM employees;
Expected result: 49750.00
The query calculates the average salary of all eight employees.
8.4 Calculate Average Bonus
SELECT AVG(bonus) AS average_bonus
FROM employees;
Expected result: approximately 3916.67
AVG(bonus) excludes NULL bonus values from both the sum and the count used in the average. It does not treat NULL as zero automatically.
8.5 Calculate Average Salary by Department
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department;
This query calculates the average salary separately for IT, HR, Finance, and Sales.
8.6 AVG(DISTINCT expression)
AVG(DISTINCT expression) calculates the average using distinct non-NULL numeric values only.
SELECT AVG(DISTINCT salary) AS average_distinct_salary
FROM employees;
It is useful only when the business question specifically concerns distinct values rather than every employee's salary.
9. MIN() Function
9.1 What Is MIN()?
The MIN() function returns the smallest value in the selected set of values. It is useful for finding the lowest salary, lowest product price, earliest date, or minimum recorded score.
9.2 Syntax of MIN()
MIN(expression)
MIN(DISTINCT expression)
9.3 Find the Lowest Salary
SELECT MIN(salary) AS lowest_salary
FROM employees;
Expected result: 35000.00
Kabir has the lowest salary among the employees in the sample table.
9.4 Find the Lowest Salary by Department
SELECT
department,
MIN(salary) AS minimum_salary
FROM employees
GROUP BY department;
This query returns the minimum salary for each department.
9.5 MIN() with Text and Dates
MIN() is not limited to numeric columns. For text, it returns the minimum according to the applicable string comparison and collation rules. For dates, it returns the earliest date value.
SELECT MIN(employee_name) AS minimum_name
FROM employees;
SELECT MIN(hire_date) AS earliest_hire_date
FROM employees;
The second query assumes that the employees table contains a hire_date column.
10. MAX() Function
10.1 What Is MAX()?
The MAX() function returns the largest value in a selected set. It is frequently used to identify the highest salary, largest order, most expensive product, latest date, or highest examination score.
10.2 Syntax of MAX()
MAX(expression)
MAX(DISTINCT expression)
10.3 Find the Highest Salary
SELECT MAX(salary) AS highest_salary
FROM employees;
Expected result: 65000.00
Meera has the highest salary among the employees in the sample table.
10.4 Find the Highest Salary by Department
SELECT
department,
MAX(salary) AS maximum_salary
FROM employees
GROUP BY department;
This query identifies the highest salary in each department.
10.5 MAX() with Dates
MAX() can be used with a date column to find the latest recorded date.
SELECT MAX(order_date) AS latest_order_date
FROM orders;
This query assumes that an orders table with an order_date column exists.
11. Difference Between COUNT(), SUM(), AVG(), MIN(), and MAX()
| Function |
What It Returns |
Example |
Business Use |
| COUNT() |
Number of rows or non-NULL values. |
COUNT(*) |
Count employees or orders. |
| SUM() |
Total of numeric values. |
SUM(salary) |
Calculate payroll expenses. |
| AVG() |
Average of numeric values. |
AVG(salary) |
Calculate average salary. |
| MIN() |
Smallest value. |
MIN(salary) |
Find the lowest salary. |
| MAX() |
Largest value. |
MAX(salary) |
Find the highest salary. |
These functions can be used together in one SELECT query to generate a compact summary of a dataset.
SELECT
COUNT(*) AS total_employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employees;
12. Understanding NULL Values in Aggregate Functions
NULL represents a missing or unknown value. Most MySQL aggregate functions ignore NULL values when calculating results. COUNT(*) is an important exception because it counts rows regardless of whether columns contain NULL.
| Function or Expression |
Behavior with NULL |
COUNT(*) |
Counts every row. |
COUNT(column) |
Counts only non-NULL values in that column. |
SUM(column) |
Ignores NULL values; returns NULL if there are no non-NULL values to sum. |
AVG(column) |
Ignores NULL values when calculating the average. |
MIN(column) |
Ignores NULL values when finding the minimum; returns NULL if no non-NULL value is available. |
MAX(column) |
Ignores NULL values when finding the maximum; returns NULL if no non-NULL value is available. |
12.1 Compare COUNT(*) and COUNT(bonus)
SELECT
COUNT(*) AS all_rows,
COUNT(bonus) AS known_bonus_values
FROM employees;
The first expression counts all eight rows. The second counts only the six rows whose bonus is not NULL.
12.2 Replace a NULL Aggregate Result
When no non-NULL values are available, SUM() can return NULL. If the business requirement calls for displaying zero, IFNULL() can provide a fallback.
SELECT
IFNULL(SUM(bonus), 0) AS total_bonus
FROM employees
WHERE department = 'Marketing';
This query returns zero if no matching bonus values are available. Remember that a fallback value changes the displayed result and should match the business meaning of the report.
13. Using Aggregate Functions with WHERE
The WHERE clause filters individual rows before the aggregate function calculates its result. This is useful when you need a summary for a specific department, city, date range, or category.
13.1 Total Salary for IT Employees
SELECT SUM(salary) AS it_total_salary
FROM employees
WHERE department = 'IT';
13.2 Average Salary Above a Minimum Condition
SELECT AVG(salary) AS average_salary
FROM employees
WHERE salary >= 45000;
Only employees whose salary is at least 45000 are included in the calculation.
13.3 Count Employees in Mumbai
SELECT COUNT(*) AS mumbai_employees
FROM employees
WHERE city = 'Mumbai';
13.4 Find the Highest Salary in Finance
SELECT MAX(salary) AS finance_highest_salary
FROM employees
WHERE department = 'Finance';
14. Using Aggregate Functions with GROUP BY
14.1 What Is GROUP BY?
GROUP BY organizes rows with the same value in one or more columns into groups. Aggregate functions then calculate a result for each group.
For example, instead of calculating one total salary for the entire company, GROUP BY department calculates a separate total for IT, HR, Finance, and Sales.
14.2 Basic Syntax
SELECT
grouping_column,
aggregate_function(expression)
FROM table_name
GROUP BY grouping_column;
14.3 Total Salary by Department
SELECT
department,
SUM(salary) AS total_salary
FROM employees
GROUP BY department;
14.4 Employee Count by Department
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
14.5 Average Salary by City
SELECT
city,
AVG(salary) AS average_salary
FROM employees
GROUP BY city;
14.6 Multiple Aggregate Functions with GROUP BY
SELECT
department,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS minimum_salary,
MAX(salary) AS maximum_salary
FROM employees
GROUP BY department;
This query creates a detailed salary summary for every department.
15. Using Aggregate Functions with HAVING
15.1 What Is HAVING?
HAVING filters groups after GROUP BY and aggregate calculations have been applied. It is useful when you want to display only groups that meet a condition based on their totals, averages, or counts.
15.2 Syntax
SELECT
grouping_column,
aggregate_function(expression)
FROM table_name
GROUP BY grouping_column
HAVING aggregate_condition;
15.3 Departments with Total Salary Above 100000
SELECT
department,
SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;
Only departments whose total salary exceeds 100000 appear in the result.
15.4 Departments with More Than One Employee
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 1;
15.5 Departments with Average Salary Above 45000
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 45000;
15.6 Difference Between WHERE and HAVING
| WHERE |
HAVING |
| Filters individual rows before grouping. |
Filters groups after grouping. |
| Usually applies conditions to ordinary column values. |
Commonly applies conditions to aggregate results. |
Example: WHERE city = 'Mumbai' |
Example: HAVING SUM(salary) > 100000 |
16. Sorting Aggregate Results with ORDER BY
ORDER BY sorts the rows returned by an aggregate query. You can sort by a grouping column or by an aggregate result.
16.1 Sort Departments by Total Salary
SELECT
department,
SUM(salary) AS total_salary
FROM employees
GROUP BY department
ORDER BY total_salary DESC;
DESC sorts the results from highest to lowest total salary. Use ASC for ascending order.
16.2 Find the Departments with the Highest Average Salary
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
ORDER BY average_salary DESC;
16.3 Display Only the Top Two Departments by Total Salary
SELECT
department,
SUM(salary) AS total_salary
FROM employees
GROUP BY department
ORDER BY total_salary DESC
LIMIT 2;
LIMIT restricts the number of rows in the final result. In this query, the two departments with the highest total salaries are returned.
17. Aggregate Functions with DISTINCT
DISTINCT can be used within several aggregate functions to remove duplicate expression values before the calculation.
17.1 Count Unique Cities
SELECT COUNT(DISTINCT city) AS unique_cities
FROM employees;
The result is 3 because the employees are located in Mumbai, Pune, and Delhi.
17.2 Sum Distinct Numeric Values
SELECT SUM(DISTINCT salary) AS total_distinct_salaries
FROM employees;
This query adds each distinct salary value once. If two employees earn the same salary, that salary is included only once in the result.
17.3 Average Distinct Values
SELECT AVG(DISTINCT salary) AS average_distinct_salary
FROM employees;
This calculates the average of unique salary values rather than the average salary across all employees. Understand the business question before using DISTINCT in a calculation.
18. Conditional Aggregation
Conditional aggregation calculates summaries for rows that meet specified conditions. MySQL's IF() or CASE expressions can be used inside aggregate functions to build flexible reports.
18.1 Count Employees by Department in One Row
SELECT
COUNT(*) AS total_employees,
SUM(CASE WHEN department = 'IT' THEN 1 ELSE 0 END) AS it_employees,
SUM(CASE WHEN department = 'HR' THEN 1 ELSE 0 END) AS hr_employees,
SUM(CASE WHEN department = 'Finance' THEN 1 ELSE 0 END) AS finance_employees
FROM employees;
The query returns one row with the total employee count and separate counts for IT, HR, and Finance.
18.2 Calculate Total Salary for Selected Departments
SELECT
SUM(CASE WHEN department = 'IT' THEN salary ELSE 0 END) AS it_salary,
SUM(CASE WHEN department = 'HR' THEN salary ELSE 0 END) AS hr_salary,
SUM(CASE WHEN department = 'Finance' THEN salary ELSE 0 END) AS finance_salary
FROM employees;
Conditional aggregation is useful when building compact dashboards and reports with several related metrics.
18.3 Count Employees with a Bonus
SELECT
COUNT(*) AS total_employees,
COUNT(bonus) AS employees_with_known_bonus,
SUM(CASE WHEN bonus > 0 THEN 1 ELSE 0 END) AS employees_with_positive_bonus
FROM employees;
These three expressions answer different questions. COUNT(*) counts all employees, COUNT(bonus) counts non-NULL bonus values, and the conditional SUM counts employees whose bonus is greater than zero.
19. Aggregate Functions and Data Types
Aggregate functions behave differently depending on the type of data being processed.
- Integer and decimal values: Commonly used with SUM(), AVG(), MIN(), and MAX().
- Text values: MIN() and MAX() compare strings according to the applicable collation and comparison rules.
- Date values: MIN() can find the earliest date, while MAX() can find the latest date.
- NULL values: Most aggregate functions ignore NULL values; COUNT(*) counts rows regardless.
SUM() and AVG() are intended for numeric calculations. They should not be used directly on date or time values to calculate meaningful date/time totals. For temporal calculations, convert values into appropriate numeric units first when necessary.
20. Common Mistakes and Troubleshooting
| Mistake |
Problem |
Correct Approach |
| Using COUNT(column) to count every row |
NULL values in that column are excluded. |
Use COUNT(*) to count rows. |
| Assuming SUM() treats NULL as zero in every situation |
SUM() ignores NULL values and may return NULL when no non-NULL input is available. |
Use IFNULL(SUM(column), 0) when zero is the correct reporting fallback. |
| Using WHERE with an aggregate condition |
WHERE filters rows before aggregation and generally cannot be used to filter an aggregate result in the same query block. |
Use HAVING for aggregate conditions. |
| Forgetting GROUP BY |
Results may be summarized across all rows rather than by category. |
Add GROUP BY when separate results are needed for each category. |
| Using SUM(DISTINCT) without checking the business meaning |
Legitimate repeated values may be counted only once. |
Use DISTINCT only when unique values are the intended input. |
| Selecting non-grouped columns in aggregate queries |
Depending on SQL mode and query structure, MySQL may reject the query or return an unsuitable value. |
Select grouping columns and aggregate expressions, or use a valid functional dependency. |
| Assuming AVG() includes NULL as zero |
NULL values are excluded from the average. |
Use an explicit expression such as AVG(IFNULL(column, 0)) only if missing values should count as zero. |
| Misreading MIN() or MAX() on text |
String comparison follows collation and comparison rules rather than numeric meaning. |
Use an appropriate numeric column or explicit conversion when required. |
20.1 Debugging an Aggregate Query
If an aggregate query returns unexpected results, check the following:
- Confirm that the query is reading from the correct table.
- Run a SELECT query to inspect the underlying records.
- Check whether NULL values are present in the relevant columns.
- Verify that WHERE conditions include the intended rows.
- Check that GROUP BY uses the correct grouping columns.
- Confirm whether DISTINCT is required.
- Check whether the average should exclude missing values or treat them as zero.
- Verify the final sorting and LIMIT conditions.
21. Best Practices for Aggregate Functions
- Use meaningful aliases such as
total_salary, average_sales, and employee_count.
- Use COUNT(*) when the requirement is to count all rows.
- Use COUNT(column) when the requirement is to count non-NULL values in a specific column.
- Understand how NULL values affect each calculation.
- Use GROUP BY to produce category-wise summaries.
- Use HAVING to filter groups according to aggregate results.
- Use WHERE to filter source records before aggregate calculations.
- Use DISTINCT only when duplicate values should be excluded from the calculation.
- Choose numeric data types appropriate for the precision required by the application.
- Validate totals against sample records when building reports.
- Use indexes and review query execution plans when working with large tables.
- Avoid selecting arbitrary non-grouped columns in aggregate queries.
- Use clear business definitions for metrics such as average salary, total revenue, and number of active customers.
22. Practical Mini Project: Employee Statistics Report
Project Objective: Create a department-level employee report using aggregate functions in MySQL.
22.1 Project Requirements
- Calculate the total number of employees.
- Calculate total salary for the company.
- Calculate the average, minimum, and maximum salary.
- Calculate total and average bonus.
- Calculate employee counts by department.
- Display only departments with more than one employee.
- Sort departments by total salary in descending order.
22.2 Generate a Company-Wide Summary
SELECT
COUNT(*) AS total_employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary,
SUM(bonus) AS total_known_bonus,
AVG(bonus) AS average_known_bonus
FROM employees;
22.3 Generate a Department Summary
SELECT
department,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS minimum_salary,
MAX(salary) AS maximum_salary
FROM employees
GROUP BY department
ORDER BY total_salary DESC;
22.4 Filter Departments
SELECT
department,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING COUNT(*) > 1
ORDER BY total_salary DESC;
22.5 Project Learning Outcomes
After completing this project, learners will understand how aggregate functions work together to produce company-wide and department-level summaries. They will also gain practical experience with NULL values, grouping, filtering, and sorting summarized results.
23. Practice Exercises
Use the sample employees table to complete the following tasks:
- Count the total number of employee records.
- Count how many employees have a non-NULL bonus.
- Count the number of unique cities.
- Calculate the total salary of all employees.
- Calculate the average salary of all employees.
- Find the lowest salary in the company.
- Find the highest salary in the company.
- Calculate total salary for the HR department.
- Calculate the average salary for employees in Mumbai.
- Find the number of employees in each department.
- Display departments whose total salary exceeds 100000.
- Display departments with an average salary above 45000.
- Sort departments by employee count from highest to lowest.
- Calculate total salary for IT and Finance using conditional aggregation.
- Compare COUNT(*) with COUNT(bonus).
24. Practice Exercise Solutions
Solution 1: Count all employees
SELECT COUNT(*) AS total_employees
FROM employees;
Solution 2: Count non-NULL bonuses
SELECT COUNT(bonus) AS known_bonus_count
FROM employees;
Solution 3: Count unique cities
SELECT COUNT(DISTINCT city) AS unique_cities
FROM employees;
Solution 4: Total salary
SELECT SUM(salary) AS total_salary
FROM employees;
Solution 5: Average salary
SELECT AVG(salary) AS average_salary
FROM employees;
Solution 6: Lowest salary
SELECT MIN(salary) AS lowest_salary
FROM employees;
Solution 7: Highest salary
SELECT MAX(salary) AS highest_salary
FROM employees;
Solution 8: Total salary for HR
SELECT SUM(salary) AS hr_total_salary
FROM employees
WHERE department = 'HR';
Solution 9: Average salary in Mumbai
SELECT AVG(salary) AS mumbai_average_salary
FROM employees
WHERE city = 'Mumbai';
Solution 10: Employee count by department
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Solution 11: Departments with total salary above 100000
SELECT
department,
SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;
Solution 12: Departments with average salary above 45000
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 45000;
Solution 13: Sort by employee count
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department
ORDER BY employee_count DESC;
Solution 14: Total salaries for IT and Finance
SELECT
SUM(CASE WHEN department = 'IT' THEN salary ELSE 0 END) AS it_salary,
SUM(CASE WHEN department = 'Finance' THEN salary ELSE 0 END) AS finance_salary
FROM employees;
Solution 15: Compare total rows and known bonuses
SELECT
COUNT(*) AS total_rows,
COUNT(bonus) AS non_null_bonus_rows
FROM employees;
25. Interview Questions and Answers
Q1. What is an aggregate function in MySQL?
An aggregate function performs a calculation on multiple values or rows and returns a summarized result.
Q2. Name five commonly used aggregate functions.
COUNT(), SUM(), AVG(), MIN(), and MAX().
Q3. What is the purpose of COUNT()?
COUNT() counts rows or non-NULL values, depending on the expression supplied.
Q4. What is the difference between COUNT(*) and COUNT(column)?
COUNT(*) counts all rows, whereas COUNT(column) counts only rows where that column is not NULL.
Q5. What does SUM() do?
SUM() calculates the total of numeric values, excluding NULL values.
Q6. How is AVG() calculated?
AVG() calculates the arithmetic mean by dividing the sum of non-NULL values by the number of non-NULL values.
Q7. What is the purpose of MIN()?
MIN() returns the smallest value in the selected set.
Q8. What is the purpose of MAX()?
MAX() returns the largest value in the selected set.
Q9. Do aggregate functions ignore NULL values?
Most aggregate functions ignore NULL values. COUNT(*) counts rows regardless of NULL values in individual columns.
Q10. What happens when SUM() has no non-NULL values to add?
SUM() returns NULL when there are no non-NULL input values, including when the input set contains no rows.
Q11. What is GROUP BY used for?
GROUP BY groups rows with matching values so aggregate functions can calculate separate results for each group.
Q12. What is the difference between WHERE and HAVING?
WHERE filters individual rows before aggregation. HAVING filters groups based on aggregate conditions after grouping.
Q13. What does COUNT(DISTINCT city) return?
It returns the number of distinct non-NULL city values.
Q14. Can MIN() and MAX() work with dates?
Yes. MIN() can return the earliest date and MAX() can return the latest date in the selected set.
Q15. What is conditional aggregation?
Conditional aggregation uses expressions such as CASE inside aggregate functions to calculate summaries for records that meet particular conditions.
Q16. What is the purpose of ORDER BY in an aggregate query?
ORDER BY sorts the summarized result, such as arranging departments by total salary from highest to lowest.
Q17. What does SUM(DISTINCT salary) do?
It adds each distinct non-NULL salary value once. Duplicate salary values are not added repeatedly.
Q18. Why are aggregate functions useful in reporting?
They summarize large datasets into useful metrics, such as totals, counts, averages, minimums, and maximums, making reports easier to interpret.
26. Quick Revision Checklist
- Aggregate functions summarize multiple values into a result.
- COUNT(*) counts all rows.
- COUNT(column) counts non-NULL values in a column.
- COUNT(DISTINCT column) counts unique non-NULL values.
- SUM() calculates a total.
- AVG() calculates an average while excluding NULL values.
- MIN() returns the smallest value.
- MAX() returns the largest value.
- Most aggregate functions ignore NULL values.
- WHERE filters source rows before aggregation.
- GROUP BY creates groups for separate aggregate calculations.
- HAVING filters grouped results.
- ORDER BY sorts aggregate results.
- DISTINCT removes duplicate expression values before supported aggregate calculations.
- Conditional aggregation uses CASE or IF expressions inside aggregate functions.
- Always verify whether missing values should be ignored, replaced, or reported separately.
27. Conclusion
Aggregate functions are essential tools for analyzing and summarizing data in MySQL. COUNT(), SUM(), AVG(), MIN(), and MAX() make it possible to calculate record counts, totals, averages, and value ranges without manually processing every row.
When combined with WHERE, GROUP BY, HAVING, ORDER BY, and DISTINCT, aggregate functions support more advanced queries and meaningful business reports. Understanding how these functions treat NULL values is equally important for producing accurate results.
Practice the examples and exercises in these notes to develop confidence in writing aggregate queries for employee management, sales reporting, finance, inventory, and other database applications.
28. Additional Learning Resources